package service

import (
	"github.com/astaxie/beego/orm"
	"net/url"
	"strconv"
	"time"
	"anban/models"
)

// 获取验证码信息
func GetVerifyCodeInfo(p map[string]interface{}) *models.VerifyCode {
	o := orm.NewOrm()
	verifyCode := &models.VerifyCode{}
	qs := o.QueryTable("VerifyCode")
	if _, ok := p["relation"]; ok && p["relation"].(bool) {
		qs = qs.RelatedSel()
	}
	if _, ok := p["id"]; ok {
		qs = qs.Filter("id", p["id"])
	}
	if _, ok := p["ip"]; ok {
		qs = qs.Filter("ip", p["ip"])
	}
	if _, ok := p["key"]; ok {
		qs = qs.Filter("key", p["key"])
	}
	if _, ok := p["code"]; ok {
		qs = qs.Filter("code", p["code"])
	}
	qs.One(verifyCode)
	if _, ok := p["convert"]; ok && p["convert"].(bool) {
		if verifyCode.Id > 0 {
			verifyCode.SendTimeShow = verifyCode.SendTime.Format("2006-01-02 15:04:05")
		}
	}
	return verifyCode
}

// 添加验证码
func AddVerifyCode(input url.Values) (int64, error) {
	o := orm.NewOrm()
	verifyCode := &models.VerifyCode{}
	if _, ok := input["ip"]; ok {
		verifyCode.Ip = input["ip"][0]
	}
	if _, ok := input["key"]; ok {
		verifyCode.Key = input["key"][0]
	}
	if _, ok := input["code"]; ok {
		verifyCode.Code = input["code"][0]
	}
	if _, ok := input["count"]; ok {
		verifyCode.Count, _ = strconv.Atoi(input["count"][0])
	}
	return o.Insert(verifyCode)
}

// 修改验证码信息
func EditVerifyCode(input url.Values) (int64, error) {
	o := orm.NewOrm()
	p := orm.Params{}
	for k, v := range input {
		if k == "id" || k == "_xsrf" {
			continue
		}
		p[k] = v[0]
	}
	p["send_time"] = time.Now().Format("2006-01-02 15:04:05")
	return o.QueryTable("VerifyCode").Filter("id", input["id"][0]).Update(p)
}

// 获取验证码列表
func GetVerifyCodeList(p map[string]interface{}) (int64, []*models.VerifyCode) {
	var verifyCodeList []*models.VerifyCode
	o := orm.NewOrm()
	qs := o.QueryTable("VerifyCode")
	if _, ok := p["relation"]; ok && p["relation"].(bool) {
		qs = qs.RelatedSel()
	}
	if _, ok := p["ip"]; ok {
		qs = qs.Filter("ip", p["ip"])
	}
	if _, ok := p["key"]; ok {
		qs = qs.Filter("key", p["key"])
	}
	totalCount, _ := qs.Count()
	curPage, ok := p["curPage"]
	perCount, _ := p["perCount"]
	if ok {
		start := perCount.(int) * (curPage.(int) - 1)
		qs = qs.Limit(perCount, start)
	}
	qs.OrderBy("-id").All(&verifyCodeList)
	if _, ok := p["convert"]; ok && p["convert"].(bool) {
		for _, verifyCode := range verifyCodeList {
			verifyCode.SendTimeShow = verifyCode.SendTime.Format("2006-01-02 15:04:05")
		}
	}
	return totalCount, verifyCodeList
}

// 检查验证码的有效性
func DoCheckVerifyCode(key string, code string) (res bool, msg string) {
	res, msg = true, ""
	p := map[string]interface{}{}
	p["key"] = key
	p["code"] = code
	verifyCode := GetVerifyCodeInfo(p)
	if verifyCode.Id <= 0 {
		res, msg = false, "请先获取验证码"
		return
	}
	currentTime := time.Now().Unix()
	allowTime := verifyCode.SendTime.Add(5 * time.Minute).Unix()
	if currentTime > allowTime {
		res, msg = false, "验证码已失效，请重新获取验证码"
		return
	}
	return
}
